<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import type { FormRules } from 'naive-ui';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
// import { fetchGetAllRoles } from '@/service/api';
import { $t } from '@/locales';
import type { DeptVO, PostVO, RoleVO, UserVO } from '@/service/types/system';
import type { DictDataOption } from '@/typings/global';
import { addUser, editUser, getUserInfo } from '@/service/api/system/user';
import { getPostSelect } from '@/service/api/system/post';
defineOptions({
  name: 'UserForm'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  currentId?: string | number | null | unknown;
  deptData: DeptVO[];
  sysNormalDisable: DictDataOption[];
  sysUserSex: DictDataOption[];
}
const loading = ref<boolean>(false);
const initLoading = ref<boolean>(false);
const props = defineProps<Props>();
interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.manage.user.addUser'),
    edit: $t('page.manage.user.editUser')
  };
  return titles[props.operateType];
});

type Model = Pick<
  UserVO,
  'userName' | 'postIds' | 'sex' | 'nickName' | 'roleIds' | 'phonenumber' | 'deptId' | 'email' | 'status'
>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    userName: '',
    sex: '0',
    nickName: '',
    deptId: '',
    phonenumber: '',
    email: '',
    roleIds: [],
    status: '0'
  };
}

// type RuleKey = Extract<keyof Model, 'userName' | 'nickName' | 'deptId' | 'status'>;

const rules: FormRules = {
  // userName: defaultRequiredRule,
  // sex: defaultRequiredRule,
  deptId: createRequiredRule('请选择部门'),
  nickName: createRequiredRule('请选择昵称'),
  status: createRequiredRule('请选择状态'),
  roleIds: createRequiredRule('请选择角色'),
  userName: {
    required: true,
    min: 2,
    max: 20,
    message: '用户名称长度必须介于 2 和 20 之间',
    trigger: 'blur'
  }
};

/** the enabled role options */
const roleOptions = ref<RoleVO[]>([]);
const postOptions = ref<PostVO[]>([]);
async function getRoleOptions() {
  const { error, data } = await getUserInfo('');
  if (!error) {
    const roles = data?.data.roles;
    roleOptions.value = roles;
  }
}
const featchPost = async (deptId?: number | string) => {
  const { error, data } = await getPostSelect(deptId);
  if (!error) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    postOptions.value = data.data;
  }
};
async function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.currentId) {
    // Object.assign(model, props.rowData);
    const data = await featchGetInfo();
    featchPost(data.deptId);
    Object.assign(model, data);
  }
}
// 获取数据
// eslint-disable-next-line consistent-return
async function featchGetInfo() {
  initLoading.value = true;
  const { error, data } = await getUserInfo(props.currentId as string);
  initLoading.value = false;
  if (!error) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    const userData = { ...data.data.user, roleIds: data?.data?.roleIds, postIds: data?.data?.postIds };
    return userData;
  }
}

function closeDrawer() {
  visible.value = false;
}
const submitAddUser = async (params: UserVO) => {
  const { error, data } = await addUser(params);
  loading.value = false;
  if (!error) {
    window.$message?.success(data?.msg);
  }
};
const submitEditUser = async (params: UserVO) => {
  const { error, data } = await editUser(params);
  loading.value = false;
  if (!error) {
    window.$message?.success(data?.msg);
  }
};

async function handleSubmit() {
  await validate();
  loading.value = true;
  const { ...params } = model;
  if (!props.currentId) {
    await submitAddUser(params as UserVO);
  } else {
    await submitEditUser({ ...params, userId: props.currentId } as UserVO);
  }
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getRoleOptions();
  }
});
const handleChangeDept = (value: string | number) => {
  model.deptId = value;
  featchPost(value);
  // console.log(option);
};
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NSpin :show="initLoading">
        <NForm ref="formRef" :model="model" :rules="rules">
          <NFormItem :label="$t('page.manage.user.userName')" path="userName">
            <NInput v-model:value="model.userName" :placeholder="$t('page.manage.user.form.userName')" />
          </NFormItem>
          <NFormItem label="请选择部门" path="deptId">
            <NTreeSelect
              v-model:value="model.deptId"
              filterable
              :options="props.deptData"
              key-field="id"
              label-field="label"
              children-field="children"
              :on-update:value="handleChangeDept"
            />
          </NFormItem>
          <NFormItem :label="$t('page.manage.user.nickName')" path="nickName">
            <NInput v-model:value="model.nickName" :placeholder="$t('page.manage.user.form.nickName')" />
          </NFormItem>
          <NFormItem :label="$t('page.manage.user.userGender')" path="sex">
            <NSelect
              v-model:value="model.sex"
              value-field="value"
              label-field="label"
              :options="sysUserSex"
              :placeholder="$t('page.manage.user.form.userRole')"
            />
          </NFormItem>
          <NFormItem :label="$t('page.manage.user.userPhone')" path="phonenumber">
            <NInput v-model:value="model.phonenumber" :placeholder="$t('page.manage.user.form.userPhone')" />
          </NFormItem>
          <NFormItem :label="$t('page.manage.user.userEmail')" path="email">
            <NInput v-model:value="model.email" :placeholder="$t('page.manage.user.form.userEmail')" />
          </NFormItem>
          <NFormItem :label="$t('page.manage.user.userRole')" path="roleIds">
            <NSelect
              v-model:value="model.roleIds"
              multiple
              value-field="roleId"
              label-field="roleName"
              :options="roleOptions"
              :placeholder="$t('page.manage.user.form.userRole')"
            />
          </NFormItem>
          <NFormItem label="岗位" path="postIds">
            <NSelect
              v-model:value="model.postIds"
              multiple
              value-field="postId"
              label-field="postName"
              :options="postOptions"
              :placeholder="$t('page.manage.user.form.userRole')"
            />
          </NFormItem>
          <NFormItem :label="$t('page.manage.user.userStatus')" path="status">
            <NRadioGroup v-model:value="model.status">
              <NRadioButton
                v-for="item in sysNormalDisable"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </NRadioGroup>
          </NFormItem>
        </NForm>
      </NSpin>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="loading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
